package com.mazegame.frontend;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mazegame.backend.BackendRegisterService;
import com.mazegame.backend.BackgroundPanel;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javax.swing.*;
import java.awt.*;

public class RegisterPanel extends JPanel implements GamePanel {
    private CardLayout cardLayout;
    private JPanel cardPanel;
    private JLayeredPane layeredPane;
    private static final int WIDTH = 1500;
    private static final int HEIGHT = 900;
    private JFXPanel jfxPanel;

    public RegisterPanel(CardLayout cardLayout, JPanel cardPanel) {
        this.cardLayout = cardLayout;
        this.cardPanel = cardPanel;
        //setLayout(new BorderLayout());
        initializeUI();
    }

    private void initializeUI() {
        // 使用 JLayeredPane 管理不同层级的组件
        layeredPane = new JLayeredPane();
        //layeredPane.setPreferredSize(new Dimension(WIDTH, HEIGHT));
        setLayout(new BorderLayout());
        add(layeredPane, BorderLayout.CENTER);

        // 创建背景面板并添加到最底层
        BackgroundPanel backgroundPanel = new BackgroundPanel("/img/bk.png");
        backgroundPanel.setBounds(0, 0, WIDTH, HEIGHT);
        layeredPane.add(backgroundPanel, JLayeredPane.DEFAULT_LAYER);

        // 创建 JavaFX 内容面板
        jfxPanel = new JFXPanel();
        jfxPanel.setOpaque(false); // 父容器也要透明
        jfxPanel.setBounds(0, 0, WIDTH, HEIGHT);
        layeredPane.add(jfxPanel, JLayeredPane.PALETTE_LAYER);

        Platform.runLater(() -> {
            VBox registerBox = createRegisterBox();
            //registerBox.setStyle("-fx-background-color: transparent;");
            // 设置场景背景为透明
            //Scene scene = new Scene(registerBox, WIDTH, HEIGHT, true);// true是不透明，
            Scene scene = new Scene(registerBox, WIDTH, HEIGHT, javafx.scene.paint.Color.TRANSPARENT);// 这才是透明
            jfxPanel.setScene(scene);
        });
    }

    private VBox createRegisterBox() {
        // 复制 LoginRegisterApp 中的 showRegisterScreen 方法的部分代码
        VBox registerBox = new VBox(30);
        registerBox.setPadding(new javafx.geometry.Insets(50, 20, 50, 20));
        registerBox.setAlignment(javafx.geometry.Pos.CENTER);
        registerBox.setPrefWidth(350);
        //-fx-background-color: rgba(0, 0, 0, 0);最后一个参数设置透明度
        registerBox.setStyle("-fx-background-color: rgba(0, 0, 0, 0); -fx-background-radius: 10px;"); // 透明背景

        // 注册标题
        javafx.scene.control.Label registerTitle = new javafx.scene.control.Label("创建账号");
        registerTitle.setFont(javafx.scene.text.Font.font("Arial", javafx.scene.text.FontWeight.BOLD, 67));
        registerTitle.setTextFill(javafx.scene.paint.Color.web("#FFD700"));

        // 用户名输入（使用提示文字）
        javafx.scene.control.TextField usernameField = creatInputBox("用户名");

        // 密码输入（使用提示文字）
        javafx.scene.control.PasswordField passwordField = creatPasswordBox("密码");

        // 确认密码输入（使用提示文字）
        javafx.scene.control.PasswordField confirmPasswordField = creatPasswordBox("确认密码");

        // 注册按钮
        javafx.scene.control.Button registerButton = creatButton("注册");
        // 注册按钮点击事件
        registerButton.setOnAction(e -> {
            String username = usernameField.getText();
            String password = passwordField.getText();
            String confirmPassword = confirmPasswordField.getText();

            // 表单验证
            if (username.isEmpty() || password.isEmpty() || confirmPassword.isEmpty()) {
                showAlert("请填写所有字段");
                return;
            }
            if (!password.equals(confirmPassword)) {
                showAlert("两次输入的密码不一致");
                return;
            }
            if (password.length() < 6) {
                showAlert("密码长度至少为6个字符");
                return;
            }

            // 调用后端注册服务
            String jsonResponse = BackendRegisterService.register(username, password);

            try {
                JsonObject obj = JsonParser.parseString(jsonResponse).getAsJsonObject();
                String status = obj.get("status").getAsString();

                if ("success".equals(status)) {
                    showAlert("注册成功！您现在可以登录了");
                    // 清除输入框内容
                    usernameField.clear();
                    passwordField.clear();
                    confirmPasswordField.clear();
                    cardLayout.show(cardPanel, "LOGINPANEL");
                } else {
                    String message = obj.get("message").getAsString();
                    showAlert(message);
                }
            } catch (Exception ex) {
                showAlert("网络异常，请检查连接");
                ex.printStackTrace();
            }
        });


        // 返回登录链接
        javafx.scene.layout.HBox loginBox = new javafx.scene.layout.HBox(5);
        loginBox.setAlignment(javafx.geometry.Pos.CENTER);

        javafx.scene.control.Label loginLabel = new javafx.scene.control.Label("已有账号？");
        loginLabel.setFont(javafx.scene.text.Font.font("KaiTi", 24));
        loginLabel.setTextFill(javafx.scene.paint.Color.rgb(0, 211, 210));

        javafx.scene.control.Button loginButton = new javafx.scene.control.Button("返回登录");
        loginButton.setFont(javafx.scene.text.Font.font("KaiTi", javafx.scene.text.FontWeight.BOLD, 24));
        loginButton.setTextFill(javafx.scene.paint.Color.rgb(0, 211, 210));
        loginButton.setStyle("-fx-background-color: transparent; -fx-underline: true;");

        // 返回登录按钮点击事件
        loginButton.setOnAction(e -> {
            cardLayout.show(cardPanel, "LOGINPANEL");
        });

        loginBox.getChildren().addAll(loginLabel, loginButton);

        // 添加所有元素到注册面板（使用VBox保持间距）
        javafx.scene.layout.VBox inputContainer = new javafx.scene.layout.VBox(20);
        inputContainer.setAlignment(javafx.geometry.Pos.CENTER);
        inputContainer.getChildren().addAll(usernameField, passwordField, confirmPasswordField);

        registerBox.getChildren().addAll(registerTitle, inputContainer, registerButton, loginBox);

        return registerBox;
    }

    private void showAlert(String message) {
        javafx.scene.control.Alert alert = new javafx.scene.control.Alert(javafx.scene.control.Alert.AlertType.INFORMATION);
        alert.setTitle("提示");
        alert.setHeaderText(null);
        alert.setContentText(message);

        // 设置对话框样式
        alert.getDialogPane().setStyle("-fx-background-color: #2D3436; -fx-text-fill: white;");
        alert.getDialogPane().lookupButton(javafx.scene.control.ButtonType.OK).setStyle("-fx-background-color: #6C5CE7; -fx-text-fill: white;");

        // 设置对话框字体
        javafx.scene.control.DialogPane dialogPane = alert.getDialogPane();
        for (javafx.scene.Node node : dialogPane.getChildren()) {
            if (node instanceof javafx.scene.control.Label) {
                ((javafx.scene.control.Label) node).setFont(javafx.scene.text.Font.font("KaiTi", 24));
                ((javafx.scene.control.Label) node).setTextFill(javafx.scene.paint.Color.WHITE);
            }
        }

        alert.showAndWait();
    }

    private javafx.scene.control.TextField creatInputBox(String title){
        javafx.scene.control.TextField field = new javafx.scene.control.TextField();
        field.setPromptText(title);
        field.setPrefSize(WIDTH/3, 75);
        field.setMaxWidth(WIDTH/3);
        field.setStyle(
                "-fx-background-color: rgba(99, 110, 114, 0.5); " +
                        "-fx-text-fill: white; " +
                        "-fx-prompt-text-fill: rgba(200, 200, 200, 0.7); " +
                        "-fx-border-radius: 5; " +
                        "-fx-background-radius: 5; " +
                        "-fx-padding: 0 10; " +
                        "-fx-font-size: 24px;"
        );
        return field;
    }

    private javafx.scene.control.PasswordField creatPasswordBox(String title){
        javafx.scene.control.PasswordField passwordField = new javafx.scene.control.PasswordField();
        passwordField.setPromptText(title);
        passwordField.setPrefSize(WIDTH/3, 75);
        passwordField.setMaxWidth(WIDTH/3);
        passwordField.setStyle(
                "-fx-background-color: rgba(99, 110, 114, 0.5); " +
                        "-fx-text-fill: white; " +
                        "-fx-prompt-text-fill: rgba(200, 200, 200, 0.7); " +
                        "-fx-border-radius: 5; " +
                        "-fx-background-radius: 5; " +
                        "-fx-padding: 0 10; " +
                        "-fx-font-size: 24px;"
        );
        return passwordField;
    }

    private javafx.scene.control.Button creatButton(String title){
        javafx.scene.control.Button button = new javafx.scene.control.Button(title);
        button.setFont(javafx.scene.text.Font.font("KaiTi", javafx.scene.text.FontWeight.BOLD, 40));
        button.setTextFill(javafx.scene.paint.Color.WHITE);
        button.setPrefSize(WIDTH/3, 75);
        button.setStyle("-fx-background-color: #6C5CE7; -fx-background-radius: 5;");

        // 添加悬停效果
        button.setOnMouseEntered(e -> {
            button.setStyle("-fx-background-color: #8C7DF7; -fx-background-radius: 5;");
            button.setEffect(new javafx.scene.effect.DropShadow(10, javafx.scene.paint.Color.rgb(108, 92, 231, 0.5)));
        });

        button.setOnMouseExited(e -> {
            button.setStyle("-fx-background-color: #6C5CE7; -fx-background-radius: 5;");
            button.setEffect(null);
        });
        return button;
    }


    @Override
    public void showPanel() {
        cardLayout.show(cardPanel, "REGISTERPANEL");
    }

    @Override
    public void cleanup() {
        // 清理逻辑
    }
}